package com.remark.service.impl;
import com.itheima.entity.Result;
import com.itheima.feign.RemarkInfoFeign;
import com.remark.dao.ESManagerMapper;
import com.remark.search.pojo.RemarkImfo;
import com.remark.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private ESManagerMapper esManagerMapper;


    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Autowired
    private RemarkInfoFeign remarkInfoFeign;
    /**
     * 创建索引映射
     */
    @Override
    public void createIndexAndMapping() {
        elasticsearchTemplate.createIndex(RemarkImfo.class);
        elasticsearchTemplate.putMapping(RemarkImfo.class);
    }

    @Override
    public void importAll() {
        ExecutorService executorService = Executors.newFixedThreadPool(6);
        //获取商家总数量
        Integer count = remarkInfoFeign.count();
        Integer pageSize = 2000;
        Integer pageTotal = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        long l = System.currentTimeMillis();
        for (Integer i = 0; i < pageTotal; i++) {
            executorService.execute(new importData4Page(i + 1, pageSize));
        }

    }

    /**
     * 根据id添加指定商家
     * @param id
     */
    @Override
    public void importData2ESById(Integer id) {
        RemarkImfo infoById = remarkInfoFeign.findInfoById(id);
        esManagerMapper.save(infoById);
    }

    class importData4Page implements Runnable {

        int page;
        int size;

        public importData4Page(int page, int size) {
            this.page = page;
            this.size = size;
        }

        /**
         * 可执行类分页添加
         */
        @Override
        public void run() {
            //分页查询商家数据，导入es
            List<RemarkImfo> infoPage = remarkInfoFeign.findInfoPage(this.page, size);
            esManagerMapper.saveAll(infoPage);
            System.out.println("第" + Thread.currentThread().getName() + "个进程成功执行");
        }
    }

}
